<template>
    <el-card class="box-card">
        <!-- 顶部标题栏 -->
        <div slot="header" style="display: flex; justify-content: space-between; align-items: center;">
            <div style="font-size: 18px;">设置</div>
            <i class="el-icon-circle-close" id="closeBtn" @click="back"></i>
        </div>

        <el-tabs v-model="activeTab" type="border-card">
            <!-- 通用设置 -->
            <el-tab-pane label="通用设置" name="general">
                <div>
                    <el-form label-position="left" label-width="150px">
                        <el-form-item label="工作区名称">
                            <el-input v-model="workspaceName" style="width: 300px;" />
                            <el-button type="primary" @click="submitRename">提交</el-button>
                        </el-form-item>

                        <el-form-item label="删除工作区">
                            <el-button type="danger" @click="deleteWorkspace">删除工作区</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>

            <!-- 聊天设置 -->
            <el-tab-pane label="聊天设置" name="chat" style="overflow-y: scroll;height: 540px;">
                <div>
                    <el-form label-position="top">
                        <el-form-item label="聊天模式">
                            <el-radio-group v-model="chatMode">
                                <el-radio-button label="chat">问答</el-radio-button>
                                <el-radio-button label="query">查询</el-radio-button>
                            </el-radio-group>
                            <p style="color: #888; margin-top: 5px;">
                                {{ chatModeDescription }}
                            </p>
                        </el-form-item>


                        <el-form-item label="聊天历史记录">
                            <el-input-number v-model="openAiHistory" :min="0" />
                            <p style="color: #888; margin-top: 5px;">推荐 20，超过 45 可能导致聊天失败。</p>
                        </el-form-item>

                        <el-form-item label="聊天提示 prompt">
                            <div class="textarea-wrapper">
                                <el-input type="textarea" v-model="openAiPrompt" :rows="15" placeholder="请输入提示"
                                    class="custom-textarea" />
                            </div>
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" @click="submitChatSetting">保存设置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </el-tab-pane>
            <!-- 知识库设置 -->
            <el-tab-pane label="知识库设置" name="knowledge">
                <KnowledgeLibrarySetting :workspace="workspace"
                @workspaceChange="workspaceChange"/>
            </el-tab-pane>

        </el-tabs>
    </el-card>
</template>

<script>
import { workspacesApi,documentApi } from '../../api/aigc/index';
import KnowledgeLibrarySetting from './KnowledgeLibrarySetting.vue'
export default {
    components:{
        KnowledgeLibrarySetting
    },
    props: {
        workspace: Object // 接收当前工作区
    },
    data() {
        return {
            activeTab: 'general',
            workspaceName: '',
            chatMode: '聊天',
            openAiHistory: 20,
            openAiPrompt: '',
        };
    },
    mounted() {
        this.fetchDocuments();
    },
    methods: {
        async workspaceChange(workspace) {
            this.$emit('workspaceChange',workspace)
        },
        back() {
            this.$emit('back');
        },
        async submitRename() {
            try {
                await workspacesApi.updateWorkspace(this.workspace.slug, {
                    name: this.workspaceName
                });
                this.$message.success('工作区名称已更新');
                this.$emit('refresh'); // 通知父组件刷新
            } catch (e) {
                console.error(e);
                this.$message.error('更新失败');
            }
        },
        async deleteWorkspace() {
            try {
                await this.$confirm('此操作将永久删除该工作区及其所有内容，是否继续？', '提示', {
                    type: 'warning'
                });
                await workspacesApi.deleteWorkspace(this.workspace.slug);
                this.$message.success('工作区已删除');
                this.$emit('refresh'); // 通知父组件刷新
                this.back();
            } catch (e) {
                console.error(e);
                this.$message.error('删除失败');
            }
        },
        async submitChatSetting() {
            try {
                await workspacesApi.updateWorkspace(this.workspace.slug, {
                    openAiPrompt: this.openAiPrompt,
                    chatMode: this.chatMode,
                    openAiHistory: this.openAiHistory
                });
                this.$message.success('设置已保存');
                this.$emit('refresh');
            } catch (e) {
                console.error(e);
                this.$message.error('保存失败');
            }
        },
        async fetchDocuments() {
            const res = await documentApi.getDocuments();
            this.documentTree = [res.localFiles]; // 符合 el-tree 数据结构
            this.folderList = res.localFiles.items.filter(i => i.type === 'folder').map(f => f.name);
        },
        async handleUpload({ file }) {
            try {
                const formData = new FormData();
                formData.append('file', file);
                await documentApi.uploadDocument({ file: formData }); // 注意 file 参数为 FormData
                this.$message.success('上传成功');
                this.fetchDocuments();
            } catch (e) {
                this.$message.error('上传失败');
            }
        },
        async removeDoc(doc) {
            try {
                await documentApi.deleteDocument({ name: doc.name }); // 如果有单独删除 API
                this.$message.success('文档已删除');
                this.fetchDocuments();
            } catch (e) {
                this.$message.error('删除失败');
            }
        },
        async createFolder() {
            try {
                await documentApi.createFolder({ name: this.newFolderName });
                this.$message.success('文件夹已创建');
                this.fetchDocuments();
                this.newFolderName = '';
            } catch (e) {
                this.$message.error('创建失败');
            }
        },
        async deleteFolder() {
            try {
                await documentApi.removeFolder({ folderName: this.selectedFolderToDelete });
                this.$message.success('文件夹已删除');
                this.fetchDocuments();
            } catch (e) {
                this.$message.error('删除失败');
            }
        },
        handleDocClick(node) {
            // 可选逻辑：点击文档后做点什么，比如预览或展示 meta
            console.log('点击文档', node);
        }
    },
    watch: {
        workspace: {
            immediate: true,
            handler(val) {
                if (val) {
                    this.workspaceName = val.name;
                    this.chatMode = val.chatMode;
                    this.openAiPrompt = val.openAiPrompt || '';
                    this.openAiHistory = val.openAiHistory || 20;
                }
            }
        }
    },
    computed: {
        chatModeDescription() {
            return this.chatMode === 'chat'
                ? '问答将提供LLM的一般知识和找到的文档上下文的答案。'
                : '查询将仅提供找到的文档上下文的答案';
        }
    }
};
</script>

<style scoped>
.box-card {
    width: 100%;
    overflow-y: scroll;
}

#closeBtn {
    font-size: 18px;
    cursor: pointer;
}

#closeBtn:hover {
    color: red;
}

.textarea-wrapper {
    border: 1px solid #dcdfe6;
    border-radius: 6px;
    padding: 10px;
    background: #f9f9f9;
}

.custom-textarea>>>.el-textarea__inner {
    border: none;
    background: transparent;
    resize: none;
    font-family: 'Courier New', monospace;
    font-size: 14px;
    line-height: 1.5;
}
</style>